package com.ptl.bp.config;

import com.ptl.bp.dto.TokenData;
import com.ptl.bp.entity.UserEntity;
import com.ptl.bp.service.AuthService;
import com.ptl.bp.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/api/file/get/",
            "/api/auth/login",
            "/api/auth/register",
            "/health",
            "/swagger-ui/",
            "/v3/api-docs/",
            "/api/battery-passports/"
    );
    @Resource
    private AuthService authService;
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 放行OPTIONS请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return false;// 中断后续处理
        }

        String requestUri = request.getRequestURI();
        if (EXCLUDE_PATHS.stream().anyMatch(requestUri::startsWith)) {
            return true;
        }

        try {
            String token = request.getHeader("Authorization");
            if (StringUtils.isNotBlank(token) && token.startsWith("Bearer ")) {
                token = token.substring(7).trim();
            }
            if (StringUtils.isBlank(token)) {
                throw new BizException(ApiResult.ResStatusEnum.UNAUTHORIZED, "未提供认证令牌");
            }

            if (!authService.validateToken(token)) {
                throw new BizException(ApiResult.ResStatusEnum.UNAUTHORIZED, "验证失败");
            }
            TokenData tokenData = authService.getTokenData(token);
            UserEntity userEntity = userService.lambdaQuery()
                    .eq(UserEntity::getId, tokenData.getId())
                    .oneOpt()
                    .orElseThrow(() -> new BizException(ApiResult.ResStatusEnum.UNAUTHORIZED, "用户不存在或已被禁用"));
            GlobalUserContext.CurrentUser loginUser = new GlobalUserContext.CurrentUser();
            loginUser.setAccessToken(token);
            loginUser.setUserId(tokenData.getId());
            loginUser.setRole(userEntity.getRole());
            GlobalUserContext.setUser(loginUser);

            return true;
        } catch (BizException e) {
            throw e;
        } catch (ExpiredJwtException e) {
            throw new BizException(ApiResult.ResStatusEnum.UNAUTHORIZED, "Token失效");
        } catch (Exception e) {
            throw new BizException(ApiResult.ResStatusEnum.UNAUTHORIZED, "认证失败");
        }
    }
}
